package hars

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"salt-fish/catch"
	"salt-fish/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	title := c.PostForm("title")
	zs := models.Zs{
		Name:  name,
		Title: title,
	}
	if name == "" || title == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	models.DB.Create(&zs)

	redis_add := "redis_add" + strconv.Itoa(int(zs.Id))
	Jsoncat, _ := json.Marshal(zs)
	catch.Rdb.Set(catch.Ctx, redis_add, Jsoncat, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": zs,
	})
}

func List(c *gin.Context) {
	var zs []models.Zs
	key_list := "key_list"
	catchCount, _ := catch.Rdb.Get(catch.Ctx, key_list).Result()
	if catchCount == "" {
		models.DB.Find(&zs)
		jsondata, _ := json.Marshal(&zs)
		catch.Rdb.Set(catch.Ctx, key_list, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(catchCount), &zs)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": zs,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id = ?", id).Delete(&models.Zs{})
	key_del := "key_del" + id
	catch.Rdb.Get(catch.Ctx, key_del)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
		"data": nil,
	})
}
